package com.sunwayworld.baseline.qywx.login.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.baseline.qywx.login.QywxContactsSenderService;
import com.sunwayworld.baseline.qywx.login.QywxLimsSenderService;
import com.sunwayworld.framework.cache.redis.RedisHelper;
import com.sunwayworld.framework.security.bean.QrCodeLoginStatusDTO;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.ArrayUtils;
import com.sunwayworld.framework.utils.ServletUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.mdm.user.bean.CoreUserBean;
import com.sunwayworld.module.mdm.user.service.CoreUserService;
import com.sunwayworld.baseline.qywx.login.bean.AppInfo;
import com.sunwayworld.baseline.qywx.login.bean.EnterpriseWxConf;
import com.sunwayworld.baseline.qywx.login.bean.QywxQrCodeDTO;
import com.sunwayworld.baseline.qywx.login.service.QywxLoginService;
import com.sunwayworld.baseline.qywx.login.utils.RestUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@GikamBean
@Repository
public class QywxLoginServiceImpl implements QywxLoginService {
    private static final Logger log = LogManager.getLogger(QywxLoginServiceImpl.class);

    @Autowired
    @Lazy
    private QywxLimsSenderService qywxLimsSenderService;

    @Autowired
    @Lazy
    private QywxContactsSenderService qywxContactsSenderService;

    @Autowired
    @Lazy
    private CoreUserService coreUserService;

    @Override
    public QywxQrCodeDTO getQrCode() {
        QywxQrCodeDTO qywxQrCodeDTO = new QywxQrCodeDTO();
        qywxQrCodeDTO.setStatus("-1");
        try {
            String fileJson = RestUtil.getJsonFromFile("enterprise_wx_conf");
            EnterpriseWxConf conf = JSONObject.parseObject(fileJson, EnterpriseWxConf.class);
            // 是否开启企业微信登录（系统配置控制）
            /*if (!conf.getQywxLoginEnabled()) {
                qywxQrCodeDTO.setStatus("0");
                return qywxQrCodeDTO;
            }*/
            AppInfo appInfo = conf.getLimsAppInfo();
            String appId = URLEncoder.encode(appInfo.getCorpId(), "UTF-8");
            String agentId = URLEncoder.encode(appInfo.getAgentId(), "UTF-8");
            String redirectUri = URLEncoder.encode(this.getRedirectUrl(), "UTF-8");
            String codeUrl = String.format(conf.getCodeUrl(), appId, agentId, redirectUri);
            qywxQrCodeDTO.setCodeUrl(codeUrl);
            qywxQrCodeDTO.setStatus("1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qywxQrCodeDTO;
    }

    @Override
    public QrCodeLoginStatusDTO scan() {
        String qrToken = StringUtils.randomUUID();
        CoreUserBean user = this.getScanedUser();
        QrCodeLoginStatusDTO loginStatus = new QrCodeLoginStatusDTO();
        if (user == null) {
            loginStatus.setStatus("-2");
            return loginStatus;
        }
        loginStatus.setStatus("2");
        loginStatus.setUserId(user.getId());
        loginStatus.setUserName(user.getUserName());
        RedisHelper.put("QR_CODE_LOGIN_CACHE", qrToken, loginStatus, 60);
        loginStatus.setLoginSuccessUrl(this.getLoginSuccessUrl(qrToken));
        return loginStatus;
    }

    @Override
    public void syncQywx() {
        try {
            String fileJson = RestUtil.getJsonFromFile("enterprise_wx_conf");
            EnterpriseWxConf conf = JSONObject.parseObject(fileJson, EnterpriseWxConf.class);
            String userListUrl = conf.getUserListUrl();
            userListUrl = String.format(userListUrl, conf.getDepartment_id(), conf.getFetch_child());
            Map<String, Object> res = qywxContactsSenderService.sendBizRequest(userListUrl, null, HttpMethod.GET);
            log.info("响应JSON:{}", JSONObject.toJSONString(res));
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(res));
            JSONArray jsonArray = jsonObject.getJSONArray("userlist");
            List<CoreUserBean> coreUserBeans = new ArrayList<>();
            for (Object o : jsonArray) {
                JSONObject object = JSONObject.parseObject(o.toString());
                CoreUserBean coreUserBean = new CoreUserBean();
                coreUserBean.setUserName(object.getString("name"));
                coreUserBean.setMobile(object.getString("mobile"));
//                coreUserBean.setQywxId(object.getString("userid"));
                coreUserBeans.add(coreUserBean);
            }
            coreUserService.getDao().update(coreUserBeans, ArrayUtils.asList("mobile","qywxId"), "userName");
        } catch (Exception e) {
            log.error("Qywx sync failed", e);
        }
    }

    private CoreUserBean getScanedUser() {
        CoreUserBean coreUserBean = null;
        HttpServletRequest request = ServletUtils.getCurrentRequest();
        if (StringUtils.isEmpty(request.getParameter("code"))) return coreUserBean;
        String qywxUserId = null;
        try {
            String fileJson = RestUtil.getJsonFromFile("enterprise_wx_conf");
            EnterpriseWxConf conf = JSONObject.parseObject(fileJson, EnterpriseWxConf.class);
            String userIdUrl = conf.getUserIdUrl();
            userIdUrl = String.format(userIdUrl, request.getParameter("code"));
            Map<String, Object> res = qywxLimsSenderService.sendBizRequest(userIdUrl, null, HttpMethod.GET);
            qywxUserId = (String) res.get("UserId");
            if (qywxUserId != null) {
                List<CoreUserBean> coreUserBeans = coreUserService.getDao().selectListByOneColumnValue(qywxUserId, "qywxId");
                coreUserBean = coreUserBeans.get(0);
            }
        } catch (Exception e) {
            log.error("Qywx login failed, qywxUserId:" + qywxUserId, e);
        }
        return coreUserBean;
    }

    private String getRedirectUrl() {
        return this.getUrl() + "/qrcode/qywx-login-redirect";
    }

    private String getLoginSuccessUrl(String qrToken) {
        return this.getUrl() + "?loginType=qrCodeLogin&qrToken=" + qrToken;
    }

    private String getUrl() {
        String fileJson = RestUtil.getJsonFromFile("enterprise_wx_conf");
        EnterpriseWxConf conf = JSONObject.parseObject(fileJson, EnterpriseWxConf.class);
        return conf.getRedirectUri();
//        HttpServletRequest request = ServletUtils.getCurrentRequest();
//        return StringUtils.removeEnd(request.getRequestURL().toString(), request.getRequestURI());
    }
}
